import React, { useCallback, useEffect, useState, useContext } from 'react';
import { connect } from 'umi';
import { history } from 'umi'
import { Table, Button, Spin, Form, message, Skeleton } from 'antd';
import classNames from 'classnames';

import { BottomAction } from '@/components';
import { withRoutePage } from '@/utils/enhanceUtils';
import AuthComponent from '@/utils/auth/AuthComponent';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import OrganizationSelect from '@/components/OrganizationSelect';

import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';

import { TabMenuRouter, TabContextMenuFilter } from '@/pages/SalaryManage/components/MenuFilterRouter';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';

import { socialWageQuery, socialWageUpdate } from '@/services/salaryManage/salaryCalculate';
import { NumberSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import YearSelect from '@/pages/SalaryManage/components/YearSelect';
import EmptyOfSingapore from '@/pages/SalaryManage/components/EmptyOfSingapore';
import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import styles from '../style.less';

/** 【工时设置】权限码 */
const SALARY_EDITOR_AUTH_CODE = 'finance:setting:salary:editorialsalary';

const MENU_AUTH_CODE_MAP = {
    CN: [SALARY_EDITOR_AUTH_CODE],
    SG: [SALARY_EDITOR_AUTH_CODE]
};

const RemindSetting = () => {
    const [pageLoading, setPageLoading] = useState(false);
    const [orgLoading, setOrgLoading] = useState(false);
    const [tableList, setTableList] = useState([]);
    const [currentSelectYear, setCurrentSelectYear] = useState('');
    const [organizationTreeData, setOrganizationTreeData] = useState([]);
    const [selectOrganizationCode, setSelectOrganizationCode] = useState(null);

    const {
        store: { selectOrganizationCode: selOrgCode },
        mergeTabStore
    } = useContext(TabStoreContext);

    useEffect(() => {
        if (selOrgCode && selOrgCode !== selectOrganizationCode) {
            setSelectOrganizationCode(selOrgCode);
        }
    }, [selOrgCode]);

    const changeMonthAmt = (index, val = 0) => {
        const newTableList = tableList.map((item, ind) => {
            if (ind === index) {
                // eslint-disable-next-line no-param-reassign
                item.socialMonthAmt = val;
                // eslint-disable-next-line no-param-reassign
                item.socialYearAmt = val * 12;
            }
            return item;
        });
        setTableList(newTableList);
    };

    const columns = [
        {
            title: '城市',
            dataIndex: 'socialCityNamePath',
            key: 'socialCityNamePath',
            align: 'left'
        },
        {
            title: '社平工资(月)',
            dataIndex: 'socialMonthAmt',
            key: 'socialMonthAmt',
            align: 'right',
            render: (text, record, index) => (
                <NumberSettingInput
                    value={text}
                    thousandsSeparator=","
                    onChange={val => changeMonthAmt(index, val)}
                    maxLength={15}
                    nonNegative
                />
            )
        },
        {
            title: '社平工资(年)',
            dataIndex: 'socialYearAmt',
            key: 'socialYearAmt',
            align: 'right',
            render: text => (
                <NumberSettingInput
                    value={text}
                    nonNegative
                    thousandsSeparator=","
                    onChange={() => {}}
                    maxLength={15}
                    disabled
                />
            )
        }
    ];

    const getList = async (organizationCode, year) => {
        try {
            setPageLoading(true);
            const { code, data, msg } = await socialWageQuery(organizationCode, year);
            if (code === 10000) {
                console.log('定时器列表信息', data);
                setTableList(data || []);
            } else {
                message.error(msg);
                setTableList([]);
            }
            setPageLoading(false);
        } catch (e) {
            setPageLoading(false);
            setTableList([]);
            console.log(e);
        }
    };
    const onSave = async () => {
        setPageLoading(true);
        try {
            const { code, msg } = await socialWageUpdate({ salarySetSocialWages: tableList });
            if (code === 10000) {
                message.success('保存成功！');
            } else {
                message.error(msg);
            }
            setPageLoading(false);
        } catch (error) {
            console.log(error);
            setPageLoading(false);
        }
    };

    // 切换年份
    const onSetCurrentYear = useCallback(year => {
        setCurrentSelectYear(year);
    }, []);

    useEffect(() => {
        setOrgLoading(true);
        fetchOrganizationListAndDefault()
            .then(({ organizationResponse, defaultOrganizationCode: defaultSelectCode }) => {
                setOrganizationTreeData(organizationResponse);
                setSelectOrganizationCode(defaultSelectCode);
            })
            .finally(() => setOrgLoading(false));
    }, []);

    useEffect(() => {
        if (selectOrganizationCode && currentSelectYear) {
            mergeTabStore({
                selectOrganizationCode,
                countryNameCode: null
            });
            getList(selectOrganizationCode, currentSelectYear);
        }
    }, [selectOrganizationCode, currentSelectYear]);

    return (
        <PageHeaderWrapper type="success">
            <TabContextMenuFilter>
                <TabMenuRouter
                    authCodeMap={MENU_AUTH_CODE_MAP}
                    type="editorialSetting"
                    extraButton={
                        <div className={salaryStyle.flex}>
                            <div className={classNames([salaryStyle.flex, salaryStyle.mr12])}>
                                <OrganizationSelect
                                    isStrictly
                                    isNeedPermission
                                    style={{ width: 220 }}
                                    treeDataFromProp
                                    treeDataList={organizationTreeData}
                                    allowClear={false}
                                    dropdownMatchSelectWidth
                                    value={selectOrganizationCode}
                                    onChange={orgCode => setSelectOrganizationCode(orgCode)}
                                />
                            </div>
                            <div>
                                <Button
                                    onClick={() =>
                                        history.push({
                                            pathname: '/finance/setting/salarySetting/editorialSettingLog',
                                            state: {
                                                tabRoute: true,
                                                tabRefresh: true
                                            },
                                            query: {
                                                year: currentSelectYear,
                                                organizationCode: selectOrganizationCode
                                            }
                                        })
                                    }
                                >
                                    操作日志
                                </Button>
                            </div>
                        </div>
                    }
                >
                    <Skeleton loading={orgLoading} active>
                        <EmptyOfSingapore organizationCode={selectOrganizationCode}>
                            <Spin spinning={pageLoading}>
                                <BaseSettingProvider organizationCode={selectOrganizationCode}>
                                    <div className={styles.container}>
                                        <Form layout="inline" style={{ marginTop: '20px', marginBottom: '20px' }}>
                                            <Form.Item label="年份" style={{ width: 200 }}>
                                                {selectOrganizationCode ? (
                                                    <YearSelect
                                                        value={currentSelectYear}
                                                        onChange={onSetCurrentYear}
                                                        organizationCode={selectOrganizationCode}
                                                        size="default"
                                                    />
                                                ) : null}
                                            </Form.Item>
                                        </Form>
                                        <Table
                                            rowKey="id"
                                            bordered
                                            columns={columns}
                                            dataSource={tableList}
                                            pagination={false}
                                        />
                                    </div>
                                </BaseSettingProvider>
                                <AuthComponent code="finance:setting:salary:editorialsalary:save">
                                    <BottomAction>
                                        <Button type="primary" onClick={onSave}>
                                            保存
                                        </Button>
                                    </BottomAction>
                                </AuthComponent>
                            </Spin>
                        </EmptyOfSingapore>
                    </Skeleton>
                </TabMenuRouter>
            </TabContextMenuFilter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(connect(() => ({}))(RemindSetting));
